let qiniu = require('qiniu'),
    formidable = require('formidable'),
    express = require('express');

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
let app = express();
app.get('/', function (req, res) {
    res.render('index');
});
app.post('/', function (req, res, next) {

    let bucket = 'myblog',
        key = '',
        form = formidable.IncomingForm(),
        token,
        putPolicy;

    form.uploadDir = path.join(__dirname, 'images');
    form.keepExtensions = true

    form.parse(req, function (err, fields, files) {
        if (err) {
            console.log(err);
        }
        key = files
            .mypic
            .path
            .split(path.sep)
            .pop();
        putPolicy = new qiniu
            .rs
            .PutPolicy(bucket + ':' + key)
        // 设置回调 putPolicy.callbackUrl = 'http://localhost:81/test/callback'
        // putPolicy.callbackBody = 'filename=$(fname)&filesize=$(fsize)'

        token = putPolicy.token()

        console.log('token', token)
        let extra = new qiniu
            .io
            .PutExtra()
        qiniu
            .io
            .putFile(token, key, files.mypic.path, extra, function (err, ret) {
                if (err) {
                    console.log(err)
                }
                console.log('ret', ret);
                res.json({token: token, ret: ret, files: files, fields: fields})
            })
    })

})

app.get('/download/:key', function (req, res, next) {
    let url = 'http://xxxx.bkt.clouddn.com/' + req.params.key,
        policy = new qiniu
            .rs
            .GetPolicy();

    console.log(url);

    res.json({
        url: policy.makeRequest(url)
    })
})

app.get('/info/:key', function (req, res, next) {
    let bucket = 'myblog',
        key = req.params.key,
        client = new qiniu
            .rs
            .Client();

    client.stat(bucket, key, (err, ret) => {
        if (err) {
            console.log(err);
        }
        res.json(ret);
    })
})